/*
 * OrderLineDAO.java
 *
 * Created on March 7, 2007, 1:20 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package Data;

import java.sql.*;
import java.util.*;
/**
 *
 * @author Danny Beutler
 */
public class OrderLineDAO {
    
///////////////////////////////////////
    ///   Singleton pattern
    
    private static OrderLineDAO instance = null;
    
    /** Creates a new instance of orderLine */
    private OrderLineDAO() {
    }
    
    public static synchronized OrderLineDAO getInstance() {
        if (instance == null) {
            instance = new OrderLineDAO();
        }
        return instance;
    }
    
    
    /////////////////////////////////
    ///   CREATE
    
    public OrderLineBO create() throws Exception {
        String id = GUID.generate();
        OrderLineBO orderLine = new OrderLineBO(id);
        Cache c = Cache.getInstance();
        c.put(orderLine.getId(), orderLine);
        return orderLine;
    }
    
    public OrderLineBO create(String id){
        OrderLineBO orderLine = new OrderLineBO(id);
        Cache c = Cache.getInstance();
        c.put(orderLine.getId(),orderLine);
        return orderLine;
    }
    
    private OrderLineBO create(ResultSet rs) throws SQLException, DataException{
        OrderLineBO orderLine;
        orderLine = new OrderLineBO(rs.getString("ID"));
        //save to the cache
        Cache.getInstance().put(orderLine.getId(),orderLine);
        orderLine.setAlreadyInDB(true);
        orderLine.setConceptualProductID(rs.getString("ConceptualProductID"));
        orderLine.setOrderID(rs.getString("OrderID"));
        orderLine.setQuantity(rs.getDouble("Quantity"));
        orderLine.setStore(rs.getString("StoreID"));
        return orderLine;
    }
    
    
    /////////////////////////////////////
    ///   READ
    /**
     * This is the public read statement.  It loads an existing record
     * from the database.
     */
    public synchronized OrderLineBO read(String id) throws DataException {
        OrderLineBO orderLine;
        Connection conn;
        // check to see if id in the cache
        // if so, return it immediately
        if(Cache.getInstance().containsKey(id)){
            return (OrderLineBO) Cache.getInstance().get(id);
        }
        
        
        try {
            
            // retrieve a database connection from the pool
            conn = ConnectionPool.getInstance().get();
            
            // call read with a connection (the other read method in this class)
            orderLine = OrderLineDAO.getInstance().read(id,conn);
            
            // release the connection
            ConnectionPool.getInstance().release(conn);
            // rollback
            conn.rollback();
        }catch (ConnectionPoolException ex) {
            throw new DataException("Unable to communicate with the Database", ex);
            
        }catch (SQLException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        }
        return orderLine;
    }
    /**
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     */
    public OrderLineBO read(String id,Connection conn) throws DataException {
        OrderLineBO orderLine=null;
        // check the cache to see if the customer is in the cache
        // if so, return it immediately
        if(Cache.getInstance().containsKey(id)){
            return (OrderLineBO) Cache.getInstance().get(id);
        }
        
        try{
            PreparedStatement pstmt =conn.prepareStatement("Select * from \"Order\" WHERE id=?");
            pstmt.setString(1,id);
            
            ResultSet rs = null;
            rs = pstmt.executeQuery();
            // get a rs from an sql SELECT statement
            // if( rs.next()){convert the rs to the member}
            if(rs.next()){
                orderLine = OrderLineDAO.getInstance().create(rs);
                
                
                
                
                
                // else {handling for no customer with that GUID
            }
        }catch(SQLException e){
            //rollback
            throw new DataException("Could not retrieve record for id=" + id,e);
        }
        //release the connection back to the pool.
        return orderLine;
    }
    
    //////////////////////////////////
    ///   UPDATE
    
    /**
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an object
     * into the database.
     */
    public synchronized void save(OrderLineBO orderLine) throws DataException {
        
        try {
            // retrieve a database connection from the pool
            Connection conn=ConnectionPool.getInstance().get();
            // call save with a connection (the other save method in this class)
            save(orderLine, conn);
            // release the connection
            ConnectionPool.getInstance().release(conn);
        }catch (SQLException e) {
            // rollback
            throw new DataException("Could not save record for id=" + orderLine.getId(), e);
        }catch (ConnectionPoolException e){
            throw new DataException("Could not retrieve Connection", e);
        }
        
        // release the connection back to the pool
        
    }
    
    
    /**
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     *
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the CustomerDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.  That's why I made
     *  update and insert private rather than package level -- if you call
     *  them directly from another DAO, this DAO can't decide whether it's
     *  object needs to be inserted or updated.
     */
    synchronized void save(OrderLineBO orderLine, Connection conn) throws SQLException, DataException {
        // check the dirty flag in the object.  if it is dirty,
        // run update or insert
        if (orderLine.isDirty()) {
            if (orderLine.isAlreadyInDB()) {
                update(orderLine, conn);
            }else{
                insert(orderLine, conn);
            }
            // set the dirty flag to false now that we've saved it
            orderLine.setDirty(false);
        }
        
        // call save(bo, conn) on any subobjects (like CustomerDAO to MembershipDAO)
        /*This next line was removed because we don't have all of the code to remediate the circulare saves.
         CustomerDAO.getInstance().save(member.getCustomer(),conn);
         **/
        // touch the cache for the object
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void update(OrderLineBO orderLine,Connection conn) throws SQLException, DataException {
        // do the update statement
        PreparedStatement pstmt =conn.prepareStatement("UPDATE \"OrderLine\" SET \"ConceptualProductID\" = ?," +
                "\"OrderID\" = ?," +
                "\"Store\" = ?," +
                "\"Quantity\" = ?," +
                " WHERE \"ID\" = ?");
        
        pstmt.setString(1,orderLine.getConceptualProductID());
        pstmt.setString(2,orderLine.getOrderID());
        pstmt.setString(3,orderLine.getStore());
        pstmt.setDouble(4,orderLine.getQuantity());
        pstmt.setString(5,orderLine.getId());
        
        pstmt.executeUpdate();
        
        //Do the membership interests insertion
        
        
        System.out.println("orderLineUpdateSuccessful");
    }
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void insert(OrderLineBO orderLine,Connection conn) throws SQLException, DataException {
        // do the insert SQL statement
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO \"OrderLine\" VALUES (?,?,?,?,?)");
        
        
        pstmt.setString(1,orderLine.getId());
        pstmt.setString(2,orderLine.getConceptualProductID());
        pstmt.setString(3,orderLine.getOrderID());
        pstmt.setString(4,orderLine.getStore());
        pstmt.setDouble(5,orderLine.getQuantity());
        
        
        pstmt.executeUpdate();
        System.out.println("orderLineInsertSucessful");
        
        //Do the membership interests insertion
        // tell the object that it's now in the db (so we call update next time not insert)
        orderLine.setAlreadyInDB(true);
    }
    
    
    ////////////////////////////////////
    ///   DELETE
    
    // We have decided not to support delete because we would like the orderLines to stay in the database for data archiving.
    
    //////////////////////////////
    ///  SEARCH methods
    
}
